<!DOCTYPE html>
<html lang="en" xml:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>作业管理</title>
    <link rel="stylesheet" href="/layui/css/layui.css">
    <link rel="stylesheet" href="/css/custom.form.css">
</head>
<body>
<!--数据与分页-->
<div class="user_table_div">
    <!--多条件查询-->
    <div id="searchParam">
        <div class="layui-form-item">
            <div class="layui-input-inline">
                <input type="text" id="name" class="layui-input" autocomplete="off" placeholder="请输入作业名">
            </div>
            <div class="layui-input-inline ">
                <button class="layui-btn" id="search">查询</button>
            </div>
        </div>
    </div>
    <!--显示数据的表格-->
    <table class="layui-hide" id="user_table" lay-filter="user_table"></table>
    <!--分页相关 View-->
    <div id="laypage" class="layui-laypage-btn"></div>
</div>


<!-- 新增编辑作业View-->
<div class="panel panel-default operation_user" hidden>
    <div class="panel-heading title"></div>
    <div class="layui-card-body">
        <form class="layui-form " action="" lay-filter="deptInfo" style="width: 700px;margin-top: 10px">
            <input name="id" hidden/>
            <div class="layui-form-item">
                <label class="layui-form-label">标题</label>
                <div class="layui-input-block">
                    <input type="text" name="title" placeholder="标题" autocomplete="off"
                           class="layui-input">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">课程</label>
                <div class="layui-input-block">
                    <div id="courseId" class="xm-select-demo"></div>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">选择题目</label>
                <div class="layui-input-block">
                    <div id="demo1" class="xm-select-demo"></div>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">搜索</label>
                <div class="layui-input-block">
                    <!--数据与分页-->
                    <div class="topic_table_div ">
                        <!--多条件查询-->
                        <div id="topic-searchParam">
                            <div class="layui-form-item">
                                <div class="layui-input-inline">
                                    <input type="text" id="topic-name" class="layui-input" autocomplete="off"
                                           placeholder="请输入作业名">
                                </div>
                                <div class="layui-input-inline ">
                                    <button class="layui-btn" type="button" id="topic-search">查询</button>
                                </div>
                            </div>
                        </div>
                        <!--显示数据的表格-->
                        <table class="layui-hide" id="topic_table" lay-filter="topic_table"></table>
                        <!--分页相关 View-->
                        <div id="topic_laypage" class="layui-laypage-btn"></div>
                    </div>

                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-input-block">
                    <button type="submit" class="layui-btn" lay-submit="" lay-filter="submit">保存
                    </button>
                    <button class="layui-btn layui-btn-primary" id="btn_cancel">返回</button>
                </div>
            </div>
        </form>
    </div>
</div>

</body>
<script src="/layui/layui.js"></script>
<script src="/js/core.util.js"></script>
<script src="/js/xm-select.js"></script>
<!--新增作业按钮、批量删除 按钮-->
<script type="text/html" id="toolbar">
    <div class="layui-btn-group">
        <!--shiro:hasPermission="sys:user:add"-->
        <button type="button" class="layui-btn" lay-event="addNewUser">
            <i class="layui-icon">&#xe608;</i> 新增作业
        </button>
    </div>
    <div class="layui-btn-group">
        <!--shiro:hasPermission="sys:user:delete"-->
        <button type="button" class="layui-btn" lay-event="batchDeleted">
            <i class="layui-icon">&#xe608;</i> 批量删除
        </button>
    </div>
</script>
<!--给作业赋予角色按钮-->
<!--shiro:hasPermission="sys:user:role:update"  shiro:hasPermission="sys:user:update" shiro:hasPermission="sys:user:delete" -->
<script type="text/html" id="tool">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<script type="text/html" id="tool2">
    <a class="layui-btn layui-btn-xs" lay-event="add">添加</a>
</script>
<script>
    layui.use(['jquery', 'form', 'table', 'laypage', 'layer', 'laydate', 'tree', 'transfer', 'layedit'], function () {
        var $ = layui.jquery;
        var form = layui.form;
        var table = layui.table;
        var topicTable = layui.table;
        var laypage = layui.laypage
        var layer = layui.layer;
        var laydate = layui.laydate;
        var layedit = layui.layedit;

        layedit.set({
            uploadImage: {
                url: '/upload'
                , type: 'post'
            }
        });

        var select = xmSelect.render({
            el: '#demo1',
            name: "topicIds",
            data: [],
            filterable: true
        })

        let courseSelect = xmSelect.render({
            el: '#courseId',
            name: "courseId",
            radio: true,
            data: []
        });

        CoreUtil.sendAjax("/study/course", null, function (res) {
            let data = Array.from(res).map(data => ({name: data.name, value: data.id}));
            courseSelect.update({data})
        }, "GET", false, function (res) {
            //用户列表接口无权限回调
            layer.msg("抱歉！您暂无获取用户列表的权限");
        });

        let build = layedit.build('content');

        var searchParam = {
            current: 1,
            size: 10,
            /*以下为多条件查询参数*/
            title: null
        }

        var topicSearchParam = {
            current: 1,
            size: 10,
            /*以下为多条件查询参数*/
            title: null
        }


        //自定义验证规则
        form.verify({
            content: function (value) {
                layedit.sync(build);
            }
        });

        /**
         *  加载分页数据
         */
        function loadPageInfo() {
            CoreUtil.sendAjax("/study/job/page", searchParam, function (res) {
                //初始化分页器
                laypageTable(res.total, searchParam.current);
                if (res.records != null) {
                    loadTable(res.records);
                }
            }, "GET", false, function (res) {
                //用户列表接口无权限回调
                layer.msg("抱歉！您暂无获取用户列表的权限");
                var noAuthorityData;
                noAuthorityData = [];
                loadTable(noAuthorityData);
            });
        }

        /**
         *  加载分页数据
         */
        function loadTopicPageInfo() {
            CoreUtil.sendAjax("/study/topic/page", topicSearchParam, function (res) {
                //初始化分页器
                layTopicpageTable(res.total, topicSearchParam.current);
                if (res.records != null) {
                    loadTopicTable(res.records);
                }
            }, "GET", false, function (res) {
                //用户列表接口无权限回调
                layer.msg("抱歉！您暂无获取用户列表的权限");
                var noAuthorityData;
                noAuthorityData = [];
                loadTable(noAuthorityData);
            });
        }


        //渲染分页插件
        var laypageTable = function (count, currentPage) {
            laypage.render({
                elem: 'laypage'
                , count: count
                , limit: searchParam.size
                , layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip']
                , curr: location.hash.replace('#!currentPage=', '')     //获取起始页
                , hash: 'currentPage'                                   //自定义hash值
                , jump: function (obj, first) {
                    if (!first) {
                        searchParam.current = obj.curr;
                        searchParam.size = obj.limit;
                        loadPageInfo();
                    }
                }
            });
        };
        //渲染table
        var loadTable = function (data) {
            //展示已知数据
            table.render({
                elem: '#user_table'
                // 这个 data 为数组数据，直接 放到 data 上即可。
                , data: data
                , even: true
                , limit: data.length
                , limits: [10, 20, 30, 40, 50]
                , toolbar: '#toolbar'
                , cols: [
                    [
                        {type: 'checkbox', fixed: 'left'},
                        {field: 'id', title: 'ID', width: 300, sort: true},
                        {field: 'title', title: '作业标题', width: 230},
                        {field: 'teacherName', title: '布置作业老师', width: 230},
                        {field: "courseName", title: "课程名", width: 200},
                        {
                            field: 'createTime', title: '创建时间', minWidth: 120, templet: function
                                (item) {
                                return CoreUtil.formattime(item.createTime);
                            }
                        },
                        {
                            field: 'updateTime', title: '更新时间', minWidth: 120, templet: function
                                (item) {
                                return CoreUtil.formattime(item.updateTime);
                            }
                        },
                        {width: 300, toolbar: "#tool", title: '操作'}
                    ]
                ]
            });
        };
        loadPageInfo();

        // 渲染题目页面
        var layTopicpageTable = function (count, currentPage) {
            laypage.render({
                elem: 'topic_laypage'
                , count: count
                , limit: topicSearchParam.size
                , layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip']
                , curr: location.hash.replace('#!currentPage=', '')     //获取起始页
                , hash: 'currentPage'                                   //自定义hash值
                , jump: function (obj, first) {
                    if (!first) {
                        topicSearchParam.current = obj.curr;
                        topicSearchParam.size = obj.limit;
                        loadPageInfo();
                    }
                }
            });
        };
        var loadTopicTable = function (data) {
            //展示已知数据
            topicTable.render({
                elem: '#topic_table'
                // 这个 data 为数组数据，直接 放到 data 上即可。
                , data: data
                , even: true
                , limit: data.length
                , limits: [10, 20, 30, 40, 50]
                , cols: [
                    [
                        {type: 'checkbox', fixed: 'left'},
                        {field: 'id', title: 'ID', width: 30, sort: true},
                        {field: 'title', title: '题目标题', width: 200},
                        {
                            field: 'content', title: '题目内容', width: 200,
                            templet: function (item) {
                                return `<label id='test${item.id}' οnmοuseοver="show(${item.id},${item.content});" οnmοuseleave='closeTips();'>详细信息</label>`
                            }
                        },
                        {width: 200, toolbar: "#tool2", title: '操作'}
                    ]
                ]
            });
        }

        loadTopicPageInfo()
        //点击新增事件， 表头工具栏事件
        table.on('toolbar(user_table)', function (obj) {
            switch (obj.event) {
                case 'addNewUser':
                    $(".title").html("新增作业");
                    $(".user_table_div").hide();
                    $(".operation_user").show();
                    $(".operation_user input[name=id]").val("");
                    courseSelect.setValue([])
                    select.setValue([])
                    $(".operation_user input[name=title]").val("");
                    form.render(); //更新全部
                    break;
                case 'batchDeleted':
                    var checkStatus = table.checkStatus(obj.config.id);
                    var data = checkStatus.data;
                    if (data.length === 0) {
                        layer.msg("请选择要批量删除的作业");
                    } else {
                        var userIds = [];
                        $(data).each(function (index, item) {
                            userIds.push(item.id);
                        });
                        tipDialog(userIds, "选中的");
                    }
                    break;
            }
            ;
        });

        //编辑或新增的界面取消事件
        $("#btn_cancel").click(function () {
            //显示表格
            $(".user_table_div").show();
            //隐藏编辑窗口
            $(".operation_user").hide();
            //可以防止在表单事件操作后自动刷新
            return false;
        });

        //监听提交 新增和编辑  保存按钮
        form.on('submit(submit)', function (data) {
            //新增
            if (data.field.id === undefined || data.field.id === null || data.field.id === "") {
                CoreUtil.sendAjax("/study/job", JSON.stringify(data.field), function (res) {
                    //显示表格
                    loadPageInfo();
                    $(".user_table_div").show();
                    //隐藏编辑窗口
                    $(".operation_user").hide();
                    // 刷新页面，但是不管事儿
                    $(".layui-laypage-btn").click();
                }, "POST", false, function (res) {
                    //新增作业无权限提示
                    layer.msg("抱歉！您暂无新增作业的权限");
                });
                // 编辑
            } else {
                CoreUtil.sendAjax("/study/job", JSON.stringify(data.field), function (res) {
                    //显示表格
                    $(".user_table_div").show();
                    //隐藏编辑窗口
                    $(".operation_user").hide();
                    $(".layui-laypage-btn").click();
                }, "POST", false, function (res) {
                    //更新作业无权限提示
                    layer.msg("抱歉！您暂无编辑作业的权限");
                });
            }
            return false;
        });


        //执行查询
        $("#search").click(function () {
            searchParam.title = $("#name").val();
            searchParam.current = 1;
            loadPageInfo();
        });

        $("#topic-search").click(function () {
            topicSearchParam.title = $("#topic-name").val();
            topicSearchParam.current = 1;
            loadPageInfo();
        });


        // 操作工具栏 点击赋予角色事件事件
        table.on('tool(user_table)', function (obj) {
            var data = obj.data;
            switch (obj.event) {
                case 'edit':
                    $(".user_table_div").hide();
                    $(".operation_user").show();
                    $(".title").html("编辑作业");
                    $(".operation_user input[name=id]").val(data.id);
                    courseSelect.setValue([{name: data.courseName, value: data.courseId}])
                    $(".operation_user input[name=title]").val(data.title);
                    setTopicList(data.id);
                    form.render(); //更新全部
                    break;
                case 'del':
                    var userIds = [];
                    userIds.push(data.id);
                    tipDialog(userIds, data.name);
                    break;
            }
        });

        // 操作工具栏 点击赋予角色事件事件
        topicTable.on('tool(topic_table)', function (obj) {
            var data = obj.data;
            switch (obj.event) {
                case 'add':
                    let from = Array.from(select.options.data).filter(info => info.value !== data.id);
                    from.push({
                        name: data.id + ':' + data.title, value: data.id, selected: true
                    });
                    select.update({
                        data: from
                    })
                    break;
            }
        });

        //删除前确认对话框
        var tipDialog = function (userIds, name) {
            layer.open({
                content: '确定要删除' + name + "作业么?",
                yes: function (index, layero) {
                    layer.close(index); //如果设定了yes回调，需进行手工关闭
                    CoreUtil.sendAjax("/study/job", JSON.stringify(userIds), function (res) {
                        layer.msg(res.message);
                        $(".layui-laypage-btn").click();
                    }, "DELETE", false, function (res) {
                        //删除作业无权限
                        layer.msg("抱歉！您暂无删除作业的权限");
                    });
                }
            });
        };


        // 渲染 选中框
        var setTopicList = function (jobId) {
            CoreUtil.sendAjax("/study/topic/job", {jobId}, function (res) {
                let data = Array.from(res).map(data => ({
                    name: data.id + ':' + data.title,
                    value: data.id,
                    selected: true
                }));
                select.update({data})
                $(".layui-laypage-btn").click();
            }, "GET", false, function (res) {
                //删除作业无权限
                layer.msg("抱歉！您暂无删除作业的权限");
            });
        }
        // 渲染时间
        laydate.render({
            elem: '.createTime'
            , position: 'static'
            , change: function (value, date) { //监听日期被切换
                lay('#testView').html(value);
            }
        });
    })
    ;
</script>
</html>

